package com.mec.web.y2012.coreservlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

@WebServlet("/ShadowedTextServlet")
public class ShadowedTextServlet extends HttpServlet {

	private static final long serialVersionUID = 5432278696959643417L;

	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String wantsList = req.getParameter("showList"); 
		if(null != wantsList){
			showFontList(resp);
		}else{
			String message = req.getParameter("message");
			if((null == message) || message.isEmpty()){
				message = "Missing 'message' parameter";
			}
			String fontName = req.getParameter("fontName");
			if((null == fontName) || fontName.isEmpty()){
				fontName = "Serif";
			}
			String fontSizeString = req.getParameter("fontSize");
			int fontSize;
			try{
				fontSize = Integer.parseInt(fontSizeString);
			}catch(NumberFormatException nfe){
				fontSize = 90;
			}
			//
			resp.setContentType("image/jpeg");
			MessageImage.writeJPEG(MessageImage.makeMessageImage(message, fontName, fontSize), resp.getOutputStream());
			
		}
		
		//
		
	}

	
	private void showFontList(HttpServletResponse resp) throws IOException{
		PrintWriter out = resp.getWriter();
		//
		String docType = Constants.docType;
		String title = "Fonts Available on Server";
		out.print(docType + ServletUtilities.headWithTitle(title) + 
				"<body bgColor = \"#fdf5e6\">\n<h1>" + title + "</h1>\n<ul>"
				);
		//
		String[] fontNames = MessageImage.getFontNames();
		for(String fontName : fontNames){
			out.println("<li>" + fontName + "</li>\n");
		}
		//
		out.println("</ul></body></html");
	}


	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}



	private static final Logger logger = 
			Logger.getLogger(ShadowedTextServlet.class);
}
